package com.webcode.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.webcode.utils.JdbcUtils;

import sun.management.resources.agent;

/**
 * @param <T>
 * @ClassName BaseDaoImpl.java
 * @Description TODO
 * @Author wushaopei
 * @Date 2020年9月19日
 * @Version 1.0
 */
public abstract class BaseDaoImpl<T> {
	
	private QueryRunner queryRunner = new QueryRunner();
	
	private Class<T> type;
	
	public BaseDaoImpl(){
		// 获取带有泛型信息的父类
		ParameterizedType genericSuperclass  = (ParameterizedType) getClass().getGenericSuperclass();
		
		// 获取泛型的 Class 接口
		type = (Class<T>)genericSuperclass.getActualTypeArguments()[0];
		System.out.println(type);
	}
	/**
	 *  执行 insert 、delete、 update 语句
	 *  
	 *  @return
	 */
	public int update(String sql,Object... args){
		Connection connection = JdbcUtils.getConnection();
		try {
			return queryRunner.update(connection, sql , args);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			JdbcUtils.closeConnection(connection);
		}
		return -1;
	}
	
	/**
	 *  查询返回一个对象的 sql 语句
	 *  
	 *  @return
	 */
	public T queryForOne(String sql, Object... args){
		
		Connection connection = JdbcUtils.getConnection();
		try {
			return queryRunner.query(connection, sql,new BeanHandler<T>(type),args);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			JdbcUtils.closeConnection(connection);
		}
		return null;
	}
	
	/**
	 *  查询返回多个对象的 sql 语句
	 *  
	 *  @return
	 */
	public List<T> queryForList(String sql , Object... args){
		Connection connection = JdbcUtils.getConnection();
		try {
			return queryRunner.query(connection, sql, new BeanListHandler<T>(type),args);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			JdbcUtils.closeConnection(connection);
		}
		return null;
	}
}	
